package org.crawutils;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.imageio.ImageIO;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang.StringUtils;

public class Utils {

	public static final String lOGIN_SUCCESS="loginsuccess";
	
	public static final String lOGIN_ERROR="loginerror";
	/* 存储当前所需要的service层 */
	private static final ThreadLocal<Map<String,Object>> threadLocal = new ThreadLocal<Map<String,Object>>();

	
	
	/* 存储当前所有参数*/
	private static final ThreadLocal<Map<String,Object>> threadParam = new ThreadLocal<Map<String,Object>>();
	
	/**
	 * 得到service Map
	 * 
	 * @return
	 */
	public static Map<String,Object> getServiceMap() {
		return threadLocal.get();
	}

	/**
	 * 释放service Map
	 */
	public static void clearServiceMap() {
		threadLocal.set(null);
	}

	/**
	 * 注册ActePropertyMappingService
	 * @param service
	 */
	public static void registerService(Map<String,Object> serviceMap) {
		Map<String,Object> serviceMapGet = threadLocal.get();
		if (serviceMapGet == null) {
			if (serviceMap != null) {
				threadLocal.set(serviceMap);
			} else {
				throw new RuntimeException("the service must be not null");
			}
		}
	}

	
	
	/**
	 * 注册当前参数
	 * @param params
	 */
	public static void registerParam(Map<String,Object> params){
		threadParam.set(params);
	}
	/**
	 * 清空当前参数
	 */
	public static void clearParam(){
		threadParam.set(null);
	}
	
	/**
	 * 得到当前参数map
	 * @return
	 */
	public static Map<String,Object> getParams(){
		return threadParam.get();
	}
	/**
	 * 根据key得到value
	 * @param key
	 * @return
	 */
	public static Object getParams(String key){
		return threadParam.get().get(key);
	}
	
	/**
	 * 调用对象的set方法
	 * @param obj
	 * @param fieldName
	 * @param value
	 * @param fieldType
	 */
	public static void callSetMethod(Object obj, String fieldName,
			Object value, Class fieldType) {
		String setName = "set" + fieldName.substring(0, 1).toUpperCase()
				+ fieldName.substring(1);
		Class cls = obj.getClass();
		try {
			Method setMethod = cls
					.getMethod(setName, new Class[] { fieldType });
			setMethod.invoke(obj, value);

		} catch (SecurityException ex) {
			ex.printStackTrace();
		} catch (NoSuchMethodException nex) {
			nex.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 利用页面传值构造模拟提交参数
	 * 
	 * @param inputValues
	 * @return
	 */
	public static NameValuePair[] formInputs(Map<String, String[]> inputValues) {
		if (inputValues == null || inputValues.size() == 0) {
			return null;
		}
		Set<Entry<String, String[]>> set = inputValues.entrySet();
		List<NameValuePair> listp = new ArrayList<NameValuePair>();

		for (Entry<String, String[]> ent : set) {
			String[] values = ent.getValue();
			for (String value : values) {
				NameValuePair n = new NameValuePair(ent.getKey(), value);
				listp.add(n);
			}
		}
		NameValuePair[] nvps = new NameValuePair[listp.size()];
		for (int i = 0; i < listp.size(); i++) {
			nvps[i] = listp.get(i);
		}
		return nvps;
	}

	public static String checkCookie(HttpClient httpClient) {
		Cookie[] cookies = httpClient.getState().getCookies();
		String tmpcookies = "";
		for (Cookie c : cookies) {
			tmpcookies += c.toString() + ";";
		}
		return tmpcookies;
	}

	/**
	 * 打印每个对象的值，用来测试
	 */
	public static void printFields(Object obj) {
		StringBuffer sbf=new StringBuffer();
		
		Class cls = obj.getClass();
		Field[] fields = cls.getDeclaredFields();
		System.out.println("----------------" + cls.getName()
				+ "---------------");
		try {
			for (Field field : fields) {
				String fieldvalue = BeanUtils.getProperty(obj, field.getName());
				System.out.println(field.getName() + " : " + fieldvalue);
				sbf.append(field.getName() + " : " + fieldvalue);
			}
			

			try {
				Utils.createFile("D:\\test\\",(new Date()).getTime()+".txt",sbf.toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	/**
	 * 打印list中每个对象的值，用来测试 */
	 
	public static void printListFields(Collection list) {
	    for(Object obj:list){
	    	System.out.println("===============================================");
	    	if(obj instanceof String){
	    		System.out.println(obj);
	    	}else{
	    		printFields(obj);
	    	}
	    }		
	}
	
	/**
	 * 打印map中每个对象的值，用来测试 */
	 
	public static void printMapFields(Map<String,Object> map) {
		Set<String> keyset=map.keySet();
		for(String key:keyset){
			System.out.println("====================key: "+key+"======================");
		    
			Object vs=map.get(key);
			if(vs instanceof List){
				for(Object obj:(List)vs){
			    	System.out.println("=================================");
			    	if(obj instanceof String){
			    		System.out.println(obj);
			    	}else{
			    		printFields(obj);
			    	}
			    }	
			}
			
		}
	    		
	}
	
	

	
	public static InputStream String2InputStream(String str){
		if(StringUtils.isNotBlank(str)){
			ByteArrayInputStream input=new ByteArrayInputStream(str.getBytes());
			return input;
		}
		return null;
	}
	
	/**
	 * 验证码图片路径
	 * 
	 * @param contextPath
	 *            request.getRealPath("")
	 * @return
	 */
	public static String checkCodeImg(String contextPath,String codeUrl,HttpClient httpClient,String cookies) {
		if(httpClient==null){
			httpClient = new HttpClient();	
		}
		
		if(codeUrl==null){
			return null;
		}
		GetMethod post = new GetMethod(
				codeUrl);
		int statusCode;
		String imgurl = "";
		try {
			statusCode = httpClient.executeMethod(post);
			if (statusCode == HttpStatus.SC_OK) {
				InputStream is = post.getResponseBodyAsStream();
				BufferedImage image = ImageIO.read(is);
				File dir = new File(contextPath + "\\CheckCode\\");
				if (!dir.exists()) {
					dir.mkdir();
				}
				String imgname = System.currentTimeMillis() + ".gif";
				File imgCodeFile = new File(dir.getAbsolutePath() + "\\"
						+ imgname);
				imgurl = "\\CheckCode\\" + imgname;
				ImageIO.write(image, "gif", imgCodeFile);

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return imgurl;
	}
	
	public static void createFile(String directorpath,String fileName, String html)
			throws Exception {
		File director = new File(directorpath);
		if (!director.exists()) {
			director.mkdirs();
		}
		File f = new File(director.getAbsoluteFile() + File.separator + fileName);
		if (!f.exists()) {
			f.createNewFile();
		}
		FileOutputStream fos = new FileOutputStream(f);
		FileWriter fw = new FileWriter(f);
		fw.write(new String(html));
		fw.close();
		fw = null;
		fos.close();
	}
	
	 public static String inputStream2String(InputStream is){
	    BufferedReader in = new BufferedReader(new InputStreamReader(is));
	    StringBuffer buffer = new StringBuffer();
	    String line = "";
	    try {
			while ((line = in.readLine()) != null){
			  buffer.append(line);
			}
		} catch (IOException e) {
		    
		}
	    return buffer.toString();
	}


	
	public static String encode(String str){
		try {
			return URLEncoder.encode(str, "utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	public static  String decode(String str){
		try {
			return URLDecoder.decode(str,"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}


}
